//
//  WebViewController.m
//  ebook
//
//  Created by ChenNan on 16/3/25.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "WebViewController.h"
#import "SVProgressHUD.h"

@interface WebViewController ()<UIWebViewDelegate>

@property (nonatomic, weak) UIBarButtonItem *backItem;
@property (nonatomic, weak) UIBarButtonItem *forwardItem;
@property (nonatomic, weak) UIBarButtonItem *refreshItem;

@property (nonatomic,retain) UIWebView *webView;

@end

@implementation WebViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    if(_showConfirm)//如果显示确认按钮，则禁用返回手势
        [self enableInteractivePopGestureRecognizer:NO];
    
    [self createBackBtn];
    self.title = _webViewTitle;
    self.view.backgroundColor = [UIColor clearColor];
    
    UIWebView *webVc = [[UIWebView alloc] init];
    webVc.delegate = self;
    webVc.frame = CGRectMake(0, 0, MTScreenW, MTScreenH-(_isShowToolbar?SafeAreaBTabbarHeight:0));
    webVc.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:webVc];
    _webView = webVc;
    
    if (!_isDirectLoadReques) {
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_url]];
        [webVc loadRequest:request];
    }else{
        [webVc loadRequest:_request];
    }
    
    [self setupToolBars];
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    self.navigationController.toolbarHidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - navi back btn
- (void)createBackBtn
{
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 60, 30);
    [backBtn setImage:[UIImage imageNamed:@"back_arrow"] forState:UIControlStateNormal];
    if (_showConfirm) {
        [backBtn setTitle:@"确认" forState:UIControlStateNormal];
        backBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    }
    [backBtn setTitleColor:MTConfigColor(@"MTNavigationBar_leftItem_Color") forState:UIControlStateNormal];
    backBtn.contentHorizontalAlignment = 1;
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = item;
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
    [self enableInteractivePopGestureRecognizer:YES];//点击返回后需要启用返回手势
}

//是否启用交互手势启用
-(void)enableInteractivePopGestureRecognizer:(BOOL)enable{
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = enable;
    }
}

#pragma mark - UIWebViewDelegate
-(void)webViewDidStartLoad:(UIWebView *)webView
{
    [SVProgressHUD show];
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [SVProgressHUD dismiss];
    [self webView:webView judgeGobackWithError:error];
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    [SVProgressHUD dismiss];
    if (!_webViewTitle) {
        self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    }
    [self webView:webView judgeGobackWithError:nil];
    self.backItem.enabled = webView.canGoBack;
    self.forwardItem.enabled = webView.canGoForward;

    [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('jump-index')[0].parentNode.removeNode(document.getElementsByClassName('jump-index')[0])"];//删除主页按钮
    MTLog(@"获取节点：%@",[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('jump-index')[0]"]);
    
//    MTLog(@"页面内容：%@",[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerHTML"]);
}

//判断是否需要自动返回。加载失败或者加载成功后是空白页,则直接返回
-(void)webView:(UIWebView *)webView judgeGobackWithError:(NSError *)error{
    
    NSString *html = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerHTML"];
    if(html.length<100||error)
        [self back];
}

#pragma mark - 初始化toolBar
- (void)setupToolBars{
    
    if(_isShowToolbar)self.navigationController.toolbarHidden = NO;
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"toolbar_back_icon"] imageWithRenderingMode:UIImageRenderingModeAutomatic] style:UIBarButtonItemStylePlain target:self action:@selector(goBack)];
    backItem.enabled = NO;
    self.backItem = backItem;
    
    UIBarButtonItem *forwardItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"toolbar_forward_icon"] imageWithRenderingMode:UIImageRenderingModeAutomatic]  style:UIBarButtonItemStylePlain target:self action:@selector(goForward)];
    forwardItem.enabled = NO;
    self.forwardItem = forwardItem;
    
    UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    UIBarButtonItem *refreshItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refresh)];
    self.refreshItem = refreshItem;
    
    self.toolbarItems = @[backItem,forwardItem,flexibleItem,refreshItem];
}

//返回上一个页面
-(void)goBack {
    [self.webView goBack];
}

//前进到下一个页面
-(void)goForward {
    [self.webView goForward];
}

//刷新当前页面
-(void)refresh {
    [self.webView reload];
}


@end
